package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.Result;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.HashMap;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class MapServiceImpl implements MapService {
//    @Value("wx.tencent.cloud.map")
    private String key = "QISBZ-GT2KU-XTQVJ-GQD7L-GZB2T-R4BRX";

    @Resource
    RestTemplate restTemplate;

    @Override
    public Result<DrivingLineVo> calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        //请求腾讯提供接口，按照接口要求传递相关参数，返回需要结果
        //使用HttpClient，目前Spring封装调用工具使用RestTemplate
        //定义调用腾讯地址
        String url = "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";
        //开始位置
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("from",calculateDrivingLineForm.getStartPointLatitude()+","+calculateDrivingLineForm.getStartPointLongitude());
        //结束位置
        hashMap.put("to",calculateDrivingLineForm.getEndPointLatitude()+","+calculateDrivingLineForm.getEndPointLongitude());
        //key
        hashMap.put("key",key);

        JSONObject result = restTemplate.getForObject(url, JSONObject.class, hashMap);

        int status = result.getIntValue("status");

        if (status != 0){
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }

        //获取返回的路线
        JSONObject route = result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);

        //创建vo对象
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        //预估时间
        drivingLineVo.setDuration(route.getBigDecimal("duration"));
        //距离

        drivingLineVo.setDistance(route.getBigDecimal("distance").divideToIntegralValue(BigDecimal.valueOf(1000)));

        //路线
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));
        return Result.ok(drivingLineVo);
    }
}
